package ru.mcfr.oxygen.framework.extensions;

import ro.sync.ecss.extensions.api.AuthorAccess;
import ro.sync.ecss.extensions.api.AuthorExternalObjectInsertionHandler;
import ro.sync.ecss.extensions.api.AuthorOperationException;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.util.URLUtil;

import java.net.URL;
import java.util.List;

public class MOFExternalObjectInsertionHandler extends AuthorExternalObjectInsertionHandler {

    public void insertURLs(AuthorAccess authorAccess, List<URL> urls, int source)
            throws AuthorOperationException {
        for (URL url : urls) {
            String xmlFragment = null;
            if (authorAccess.getUtilAccess().isSupportedImageURL(url)) {
                // Insert an image element
                xmlFragment = "<image href=\"" + url.toString() + "\"/>";
            } else {
                // Insert
                xmlFragment = "<ref location=\"" + url.toString() + "\"/>";
            }
            if (xmlFragment != null) {
                // Create am image fragment
                AuthorDocumentFragment imageFragment = authorAccess.getDocumentController().createNewDocumentFragmentInContext(
                        xmlFragment, authorAccess.getCaretOffset());
                // Insert the fragment
                authorAccess.getDocumentController().insertFragment(authorAccess.getCaretOffset(), imageFragment);
            }
        }
    }

    public boolean acceptSource(AuthorAccess authorAccess, int source) {
        if (source == DND_EXTERNAL) {
            // Accept only from external source
            return true;
        }
        // For urls from other sources (Dita Maps Manager, Project) a new tab will be open.
        return false;
    }

    public boolean acceptURLs(AuthorAccess authorAccess, List<URL> urls, int source) {
        boolean accept = acceptSource(authorAccess, source);
        if (accept) {
            for (int i = 0; i < urls.size(); i++) {
                // Accept only XML and image files
                if (!authorAccess.getUtilAccess().isSupportedImageURL(urls.get(i)) &&
                        !"xml".equalsIgnoreCase(URLUtil.getExtension(urls.get(i).toString()))) {
                    accept = false;
                    break;
                }
            }
        }
        return accept;
    }
}
